package lumis.service.wsrp.producer;

import java.util.Date;

import lumis.service.wsrp.common.WSRPUtils;

import com.sun.portal.wsrp.common.LeaseTime;
import com.sun.portal.wsrp.common.stubs.v2.Lifetime;
import com.sun.portal.wsrp.common.stubs.v2.RegistrationData;
import com.sun.portal.wsrp.producer.ProducerException;
import com.sun.portal.wsrp.producer.registration.RegistrationManager;
/**
 * {@link RegistrationManager} implementation.  Overrides only addRegistration from {@link com.sun.portal.wsrp.producer.registration.impl.RegistrationManagerImpl}
 * due to domain specific issues
 * 
 * @version $Revision: 13092 $ $Date: 2011-05-28 18:19:06 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
class RegistrationManagerImpl extends com.sun.portal.wsrp.producer.registration.impl.RegistrationManagerImpl 
{
	/**
	 * Producer that needs to be used throughout execution.
	 */
	private ProducerImpl localProducer;
	
	/**
	 * Only construtor receiving a Producer.
	 * @param producer associated to this RegistrationManager.
	 * @throws ProducerException is any problems occur during processing.
	 */
	public RegistrationManagerImpl(ProducerImpl producer) throws ProducerException {
		super(producer);
		this.localProducer = producer;
	}
	
	@Override
    protected String addRegistration(RegistrationData registrationData,Lifetime lifetime) throws ProducerException {
        LeaseTime regLifeTime = new LeaseTime();
        long maxInbandLifetime = this.localProducer.getMaxInbandLifetime() + System.currentTimeMillis();
        Date maxLifetime = new Date(maxInbandLifetime);
        
        if(lifetime != null)
        {
        	Date dateFromXMLGregorianCalendar = WSRPUtils.dateFromXMLGregorianCalendar(lifetime.getTerminationTime());
        	if(dateFromXMLGregorianCalendar.before(maxLifetime))
        	{
        		regLifeTime.setTerminationTime(lifetime.getTerminationTime());
        	}
        	else
        	{
        		regLifeTime.setTerminationTime(WSRPUtils.toXMLGregorianCalendar(maxLifetime));
        	}
        		
            regLifeTime.setCurrentTime(lifetime.getCurrentTime());
            
        }
        else
        {
        	regLifeTime.setTerminationTime(WSRPUtils.toXMLGregorianCalendar(maxLifetime));
        	regLifeTime.setCurrentTime(WSRPUtils.toXMLGregorianCalendar(System.currentTimeMillis()));
        }
        return addRegistration(registrationData, true,regLifeTime);
    }
}
